package com.gykfbxxh.imovie.custom.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * 解决滑动冲突的viewpager
 *
 * @author xuxinghai
 */
public class MyViewPager extends ViewPager {

	private float mDownX;
	private float mDownY;
	private boolean isSlide;//是否禁止滑动
	
	private static final int DRAGGING_DIRECT_UNDEFINE = 0;
	private static final int DRAGGING_DIRECT_HORIZONTAL = 1;
	private static final int DRAGGING_DIRECT_VERTICAL = 2;
	private int mDraggingDirect = DRAGGING_DIRECT_UNDEFINE;
	
	public MyViewPager(Context context){
		super(context);
	}
	
	public MyViewPager(Context context, AttributeSet attrs) {
		super(context,attrs);
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			try {
				mDownX = ev.getX();
				mDownY = ev.getY();
			} catch (Exception e) {
				e.printStackTrace();
			}
			mDraggingDirect = DRAGGING_DIRECT_UNDEFINE;
			if(mDownX < 50){
				if (getParent()!=null)
				getParent().requestDisallowInterceptTouchEvent(false);
			} else {
				if (getParent()!=null)
				getParent().requestDisallowInterceptTouchEvent(true);
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if ((mDraggingDirect == DRAGGING_DIRECT_UNDEFINE && Math.abs(ev.getX()-mDownX) > 30 )|| Math.abs(ev.getY()-mDownY)>10 ) {
				try {
					boolean isDraggingHorizontal = Math.abs(ev.getX()-mDownX) > Math.abs(ev.getY()-mDownY);
					if (getParent()!=null)
                    getParent().requestDisallowInterceptTouchEvent(isDraggingHorizontal);
					mDraggingDirect = isDraggingHorizontal ? DRAGGING_DIRECT_HORIZONTAL : DRAGGING_DIRECT_VERTICAL;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL: {
			mDraggingDirect = DRAGGING_DIRECT_UNDEFINE;
			if (getParent()!=null)
			getParent().requestDisallowInterceptTouchEvent(false);			
		}
			break;
		default:
			break;
		}

		boolean flag = false;
		try {
			flag = super.dispatchTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return flag;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if(isSlide){
			return false;
		}
		boolean flag = false;
		try {
			flag = super.onTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		boolean flag = false;
		try {
			flag = super.onInterceptTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

}
